# coding:utf-8
"""mongo users"""
from mongo import users
from flask_restful import Resource
from bson import json_util
from bson.json_util import dumps
from flask import Response, request
import pymongo
import uuid
import datetime
import hashlib

class Users(Resource):

    def get(self):
        return Response(dumps(users.find().sort('name',pymongo.ASCENDING), default=json_util.default), mimetype="application/json")

    def post(self):
        user = request.get_json()
        result = users.insert_one(user)
        return str(result.inserted_id)

class User(Resource):

    def get(self, name):
        return Response(dumps(users.find({'name': name})), mimetype="application/json")

    def put(self, name):
        if name:
            user = request.get_json()
            result = users.update_one({'name': name}, {'$set': user})
            status = 200 if 1 == result.matched_count and 1 == result.modified_count else 400
            return Response(dumps(result.raw_result), status=status, mimetype="application/json")
        else:
            return Response("name can not be empty", status=400)

    def delete(self, name):
        if name:
            result = users.delete_one({'name': name})
            status = 200 if result.deleted_count == 1 else 400
            return Response(dumps(result.raw_result), status=status, mimetype="application/json")
        else:
            return Response("name can not be empty", status=400)


def str2md5(str):
    return hashlib.md5(str).hexdigest()


if __name__ == '__main__':
    pwd = str2md5('123456')
    _code_users = [
        {'name': 'GuoYang', 'desc': r"郭阳", 'pwd': pwd},
        {'name': 'ZhangPeng', 'desc': r'张鹏', 'pwd': pwd},
        {'name': 'LiuYanLi', 'desc': r'刘艳丽', 'pwd': pwd},
        {'name': 'NieFuLei', 'desc': r'聂付磊', 'pwd': pwd},
        {'name': 'LiuQiuYue', 'desc': r'刘秋月', 'pwd': pwd},
        {'name': 'XingZhengRan', 'desc': r'邢铮然', 'pwd': pwd},
        {'name': 'QiFang', 'desc': r'齐芳', 'pwd': pwd},
        {'name': 'LiQiHao', 'desc': r'李启浩', 'pwd': pwd},
        {'name': 'admin', 'desc': r'管理员', 'pwd': pwd},
    ]
    result = users.insert_many(_code_users)
    print(result)
